<template>
  <view class="w-[750rpx] bg-[#f5f7fa] min-h-screen">
    <PageHeader title="签到打卡" :showBack="true" />
    <view class="container w-[750rpx] px-[30rpx] box-border">
      <!-- 头部区域 -->

      <!-- <view
        class="header bg-gradient-to-r from-[#3498db] to-[#2980b9] text-white p-[40rpx_30rpx] rounded-b-[40rpx] mb-[40rpx]"
      >
      </view> -->

      <!-- 会员打卡视图 -->
      <view class="member-view mt-4">
        <view
          class="checkin-card bg-gradient-to-r from-[#4facfe] to-[#00f2fe] rounded-[32rpx] p-[50rpx] text-white mb-[40rpx] text-center"
        >
          <view
            class="checkin-title text-[44rpx] font-bold mb-[30rpx] flex items-center justify-center"
          >
            <IconFont
              font-class-name="iconfont"
              class-prefix="icon"
              name="weizhi"
              size="24"
              color="#fff"
              class="mr-[20rpx]"
            ></IconFont>
            今日签到任务
          </view>
          <!-- <text class="text-[32rpx]">{{ currentTask.name }}</text> -->

          <!-- <view class="distance-info text-[64rpx] font-bold my-[40rpx]">
            <text>{{ currentTask.check_range }}</text>
            <text style="font-size: 40rpx">米</text>
          </view>
          <view class="distance-label text-[28rpx] opacity-90"
            >距签到点距离</view
          > -->

          <button v-if="currentTask.memberStatus==11" 
            class="checkin-btn bg-white text-[#3498db] border-none rounded-[60rpx] py-[30rpx] text-[36rpx] font-bold w-[80%] my-[40rpx] mx-auto cursor-pointer shadow-lg transition-all duration-300"
            :class="isChecked ? 'bg-[#2ecc71] text-white' : ''"
            :disabled="isChecking || isChecked"
            @click="handleCheckin"
          >
            <text class="text-[#999]">{{
              isChecking ? "签到中..." : isChecked ? "签到成功!" : "立即签到"
            }}</text>
          </button>

          <view v-else
              class="checkin-btn bg-[#f5f5f5] text-[#999] border border-[#e0e0e0] rounded-[60rpx] py-[30rpx] text-[36rpx] font-bold w-[88%] my-[40rpx] mx-auto flex items-center justify-center cursor-not-allowed"
            >
            <text class="flex items-center justify-center">
              <text class="mr-[8rpx]">❌</text>
              未报名成功，不能签到
            </text>
          </view>

          <view>
            <text class="text-[28rpx]">签到有效范围：{{ currentTask.check_range }}米内</text>
          </view>
        </view>

        <!-- 任务详情 -->
        <view
          class="task-detail bg-white rounded-[32rpx] p-[40rpx] shadow-md mb-[40rpx]"
        >
        <view class="detail-item flex mb-[30rpx]">
            <view class="detail-label w-[200rpx] text-[#7f8c8d] text-[28rpx]"
              >发布者</view
            >
            <view class="detail-value flex-1 font-medium">{{
              currentTask.name
            }}</view>
          </view>
          <!-- <view class="detail-item flex mb-[30rpx]">
            <view class="detail-label w-[200rpx] text-[#7f8c8d] text-[28rpx]"
              ></view
            >
            <view class="detail-value flex-1 font-medium">{{
              currentTask.title
            }}</view>
          </view> -->
          <view class="detail-item flex mb-[30rpx]">
            <view class="detail-label w-[200rpx] text-[#7f8c8d] text-[28rpx]"
              >任务名称</view
            >
            <view class="detail-value flex-1 font-medium">{{
              currentTask.title
            }}</view>
          </view>
          <!-- <view class="detail-item flex mb-[30rpx]">
            <view class="detail-label w-[200rpx] text-[#7f8c8d] text-[28rpx]"
              >签到地点</view
            >
            <view class="detail-value flex-1 font-medium">{{
              currentTask.location
            }}</view>
          </view> -->
          <view class="detail-item flex mb-[30rpx]">
            <view class="detail-label w-[200rpx] text-[#7f8c8d] text-[28rpx]"
              >详细地址</view
            >
            <view class="detail-value flex-1 font-medium">{{
              currentTask.full_address
            }}</view>
          </view>
          <view class="detail-item flex mb-[30rpx]">
            <view class="detail-label w-[200rpx] text-[#7f8c8d] text-[28rpx]"
              >有效时间</view
            >
            <view class="detail-value flex-1 font-medium">
              {{currentTask.start_date}} 至 {{currentTask.end_date}} 
            </view>
          </view>
          <view class="detail-item flex mb-[30rpx]">
            <view class="detail-label w-[200rpx] text-[#7f8c8d] text-[28rpx]"
              >距签到点</view
            >
            <view class="detail-value flex-1 font-medium flex items-center">
              <text class="mr-[20rpx]">{{ distance }}米</text>
              <nut-button 
                size="small" 
                type="primary" 
                @click="refreshLocation"
                class="text-[24rpx] px-[20rpx] py-[8rpx]"
              >
                刷新
              </nut-button>
            </view>
          </view>
          <view class="detail-item flex mb-[30rpx]">
            <view class="detail-label w-[200rpx] text-[#7f8c8d] text-[28rpx]"
              >任务金额</view
            >
            <view class="detail-value flex-1 font-medium">
              <text class="text-[#f44336]">{{ currentTask.task_amount }}</text>元
            </view>
          </view>
        </view>

        <!-- 任务描述卡片 -->
        <view class="bg-white rounded-[24rpx] p-[32rpx] shadow-sm mb-[24rpx] border border-[#f0f0f0]">
          <!-- 标题部分 -->
          <view class="flex items-center mb-[20rpx] pb-[16rpx] border-b border-[#f5f7fa]">
            <text class="mr-[12rpx] text-[28rpx]">📝</text>
            <text class="text-[30rpx] font-bold text-[#333]">任务描述</text>
          </view>
          
          <!-- 描述内容 -->
          <view class="bg-[#f8f9fa] rounded-[16rpx] p-[24rpx] border-l-[6rpx] border-l-[#1890ff]">
            <text class="text-[26rpx] text-[#666] leading-[1.6] break-words">{{ currentTask.describe_str || '暂无任务描述' }}</text>
          </view>
        </view>
        <view class="h-10"></view>


        <!-- 报名列表 -->
        <view class="bg-white rounded-[24rpx] p-[32rpx] shadow-sm mb-[24rpx] border border-[#f0f0f0]">
          <view class="flex items-center mb-[20rpx] pb-[16rpx] border-b border-[#f5f7fa]">
            <text class="mr-[12rpx] text-[28rpx]">👥</text>
            <text class="text-[30rpx] font-bold text-[#333]">报名列表</text>
          </view>
          <role v-if="taskId && refreshKey" :key="refreshKey" :tid="taskId" :type="taskType"
           :publisherId="currentTask.member_id" :totalAmount="totalAmount" :isPublisher="isPublisher" 
           @list="handleGetList" @refresh="onPullDownRefresh"
           />
        </view>

        <!-- 状态和功能按钮 -->
        <view class="status-actions p-[30rpx] mb-[20rpx]" v-if="showActionButtons">
          <!-- 操作按钮区域 -->
          <view class="action-buttons flex flex-wrap gap-[20rpx]">
            <!-- 发布者操作按钮 -->
            <nut-button
              v-for="action in getPublisherActions(currentTask.status || 0)"
              :key="action"
              size="small"
              @click="handlePublisherAction(action)"
              v-if="isPublisher"
              class="action-btn"
            >
              {{ action }}
            </nut-button>

            <!-- 执行者操作按钮 -->
            <nut-button
              v-for="action in getExecutorActions(currentTask.status || 0)"
              :key="action"
              size="small"
              @click="handleExecutorAction(action)"
              v-if="isExecutor"
              class="action-btn"
            >
              {{ action }}
            </nut-button>
          </view>
        </view>

        <view
          class="bottom-bar fixed bottom-0 left-0 right-0 bg-white p-[20rpx] border-t border-gray-100 flex items-center gap-4"
        >
          <!-- 已停止招聘状态 -->
          <view v-if="currentTask.status == 5" class="flex items-center flex-1">
            <IconFont font-class-name="iconfont" class-prefix="icon" name="xinxiinfo21" size="20" class="text-[#ff9900] mr-[10rpx]" />
            <text class="text-[28rpx] text-[#ff9900]">已停止招聘，无法报名</text>
          </view>
          <!-- 正常状态 -->
          <template v-else>
            <nut-button
              class="flex-1"
              type="success"
              @click="showContactInfo"
            >
            <template #icon>
                <IconFont name="message" size="28rpx" class="mr-[10rpx]" />
            </template>
              在线咨询
            </nut-button>
            
            <nut-button 
              type="info"
              class="flex-1"
              @click="applyForJob"
              v-if="currentTask.memberStatus == 0"
            >
              立即报名
            </nut-button>
            <nut-button 
              class="flex-1"
              disabled
              v-else
            >
              已报名
            </nut-button>
          </template>
        </view>
      </view>
    </view>

    <!-- 纠纷提示弹窗 -->
    <DisputeModal
      v-model:visible="showDisputeModal"
      :title="disputeModalConfig.title"
      :description="disputeModalConfig.description"
      :actions="disputeModalConfig.actions"
      :additional-info="disputeModalConfig.additionalInfo"
      :confirm-text="disputeModalConfig.confirmText"
      :loading="disputeModalLoading"
      @confirm="handleDisputeConfirm"
      @close="handleDisputeClose"
    />

    <!-- 客服联系弹窗 -->
    <CustomerServiceModal
      v-model:visible="showCustomerServiceModal"
      @close="handleCustomerServiceClose"
    />
  </view>
</template>

<script setup>
import { ref, computed } from "vue";
import Taro, {showToast} from "@tarojs/taro";
import { IconFont } from "@nutui/icons-vue-taro";
import { useUserStore } from "@/store/user";
import { storeToRefs } from "pinia";
import { post } from "@/utils/request";
import DisputeModal from "@/components/DisputeModal.vue";
import CustomerServiceModal from "@/components/CustomerServiceModal.vue";
import { StatusActions } from "@/constants/StatusActions";
import role from "../recruit/role.vue";

const userStore = useUserStore();
const { locationObj, userInfo } = storeToRefs(userStore);

const logLocationUpdate = (source, payload) => {
  console.log("[checkin-task-detail] locationObj 更新", { source, payload });
};

// 用户身份判断
const isPublisher = ref(false);
const isExecutor = ref(false);
const totalAmount = ref(0);
const hasSignUp = ref(false);
const refreshKey = ref(1);

// 纠纷弹窗相关状态
const showDisputeModal = ref(false);
const disputeModalLoading = ref(false);
const disputeModalConfig = ref({
  title: '异议申请已提交',
  description: '我们已收到您的异议申请，平台将立即采取以下措施：',
  actions: [
    { icon: 'lock', text: '冻结当前阶段交易资金' },
    { icon: 'service', text: '客服将在24小时内联系双方' },
    { icon: 'clock', text: '纠纷处理期间暂停任务进度' }
  ],
  additionalInfo: '请准备好相关沟通记录作为证据，平台客服会通过注册手机号与您联系。',
  confirmText: '确认'
});

// 客服联系弹窗相关状态
const showCustomerServiceModal = ref(false);

// 当前签到任务信息
const currentTask = ref({
  // name: "星巴克门店签到",
  // location: "星巴克(中关村店)",
  // address: "北京市海淀区中关村大街15号",
  // timeRange: "每天 08:00 - 22:00",
  // reward: "20积分 + 星巴克9折券",
  // range: 100,
});

// 会员打卡相关数据
const distance = ref(125);
const isChecking = ref(false);
const isChecked = ref(false);

// 签到记录
const checkinRecords = ref([
  {
    date: "07-30",
    location: "星巴克(中关村店)",
    time: "10:25:34",
    status: "success",
  },
  {
    date: "07-29",
    location: "海底捞(中关村店)",
    time: "18:45:12",
    status: "success",
  },
  {
    date: "07-28",
    location: "王府井旗舰店",
    time: "15:30:45",
    status: "success",
  },
  {
    date: "07-27",
    location: "星巴克(中关村店)",
    time: "09:15:22",
    status: "fail",
  },
]);

// 成就数据
const totalCheckins = ref(28);
const consecutiveCheckins = ref(15);
const totalPoints = ref(860);

// 计算属性：是否显示操作按钮
const showActionButtons = computed(() => {
  return isPublisher.value || isExecutor.value;
});

/**
 * 获取发布者操作按钮列表
 * @param status 任务状态码
 * @returns 操作按钮数组
 */
const getPublisherActions = (status) => {
  return StatusActions[status]?.publisherActions || [];
};

/**
 * 获取执行者操作按钮列表
 * @param status 任务状态码
 * @returns 操作按钮数组
 */
const getExecutorActions = (status) => {
  return StatusActions[status]?.executorActions || [];
};

/**
 * 处理发布者操作
 * @param action 操作名称
 */
const handlePublisherAction = async (action) => {
  console.log("发布者操作:", action, currentTask.value);
  try {
    let newStatus = currentTask.value.status || 0;
    
    // 根据操作名称确定新状态
    switch (action) {
      case "审核申请":
        // 显示报名申请列表，让发布者审核
        showSignUpList();
        return;
      case "确认完成":
        newStatus = 22;
        break;
      case "有纠纷":
        // 显示纠纷弹窗
        showDisputeModal.value = true;
        return;
      case "联系平台":
        // 显示客服联系弹窗
        showCustomerServiceModal.value = true;
        return;
      default:
        showToast({ title: "未知操作", icon: "error" });
        return;
    }

    // 调用接口更新状态
    const res = await post("/check/updateStatus", {
      id: currentTask.value.id,
      status: newStatus,
    });

    if (res.code === 0) {
      // 更新本地状态
      currentTask.value.status = newStatus;
      
      showToast({ title: "操作成功", icon: "success" });
    } else {
      showToast({ title: res.message || "操作失败", icon: "error" });
    }
  } catch (error) {
    console.error("发布者操作失败:", error);
    showToast({ title: "网络错误，请重试", icon: "error" });
  }
};

/**
 * 处理执行者操作
 * @param action 操作名称
 */
const handleExecutorAction = async (action) => {
  try {
    let newStatus = currentTask.value.status || 0;
    
    // 根据操作名称确定新状态
    switch (action) {
      case "我已完成":
        newStatus = 21; // 待审核
        break;
      case "联系平台":
        // 显示客服联系弹窗
        showCustomerServiceModal.value = true;
        return;
      case "接受方案":
        const confirm = await Taro.showModal({
          title: "接受方案",
          content: "确定要接受方案吗？",
          confirmText: "确定",
          cancelText: "取消",
        });
        if (!confirm.confirm) return;
        newStatus = 22; // 确认完成
        break;
      case "拒绝方案":
        const reject = await Taro.showModal({
          title: "拒绝方案",
          content: "确定要拒绝方案吗？",
          confirmText: "确定",
          cancelText: "取消",
        });
        if (!reject.confirm) return;
        newStatus = 23; // 有纠纷
        break;
      default:
        showToast({ title: "未知操作", icon: "error" });
        return;
    }

    // 调用接口更新状态
    const res = await post("/check/updateStatus", {
      id: currentTask.value.id,
      status: newStatus,
    });

    if (res.code === 0) {
      // 更新本地状态
      currentTask.value.status = newStatus;
      
      showToast({ title: "操作成功", icon: "success" });
    } else {
      showToast({ title: res.message || "操作失败", icon: "error" });
    }
  } catch (error) {
    console.error("执行者操作失败:", error);
    showToast({ title: "网络错误，请重试", icon: "error" });
  }
};

/**
 * 处理报名列表数据
 */
const handleGetList = (list) => {
  console.log("报名列表:", list, userInfo.value.id);
  const rs = list.some(item => item.columns.member_id == userInfo.value.id);
  console.log("是否已报名:", rs);
  hasSignUp.value = !!rs;
};

/**
 * 显示报名申请列表
 */
const showSignUpList = () => {
  // 跳转到报名列表页面
  Taro.navigateTo({
    url: `/pages-detail/post/reward/role?tid=${currentTask.value.id}&isPublisher=true`
  });
};

/**
 * 处理纠纷弹窗确认
 */
const handleDisputeConfirm = async () => {
  disputeModalLoading.value = true;
  
  try {
    // 调用接口更新状态为有纠纷
    const res = await post("/check/updateStatus", {
      id: currentTask.value.id,
      status: 23,
    });

    if (res.code === 0) {
      // 更新本地状态
      currentTask.value.status = 23;
      
      showDisputeModal.value = false;
      
      showToast({ title: "异议申请已提交", icon: "success" });
    } else {
      showToast({ title: res.message || "操作失败", icon: "error" });
    }
  } catch (error) {
    console.error("提交异议申请失败:", error);
    showToast({ title: "网络错误，请重试", icon: "error" });
  } finally {
    disputeModalLoading.value = false;
  }
};

/**
 * 处理纠纷弹窗关闭
 */
const handleDisputeClose = () => {
  showDisputeModal.value = false;
};

/**
 * 处理客服联系弹窗关闭
 */
const handleCustomerServiceClose = () => {
  showCustomerServiceModal.value = false;
};

// 显示联系信息
const showContactInfo = () => {
  // Taro.showModal({
  //   title: '联系信息',
  //   content: `发布者：${currentTask.value.name || '未知'}\n联系电话：${currentTask.value.phone || '暂无'}\n微信：${currentTask.value.wechat || '暂无'}`,
  //   showCancel: false,
  //   confirmText: '确定'
  // });
  Taro.navigateTo({
    url:`/pages/message/chat?userId=${currentTask.value.member_id}`
  })
};

// 报名任务
const applyForJob = async () => {
  try {
    Taro.showLoading({ title: '报名中...' });
    const res = await post("/check/register", {taskId: currentTask.value.id});
    if (res.code == 0) {
      Taro.hideLoading();
      Taro.showToast({
        title: "申请已提交，请等待审核",
        icon: "none",
        duration: 2000,
      });
      setTimeout(() => {
        Taro.navigateBack();
      }, 1200);
    }
    else{
      Taro.showToast({ title: res.data, icon: "none", duration:2000});
    }
    
    
  } catch (error) {
    console.error('报名失败:', error);
    Taro.showToast({
      title: '网络错误，请重试',
      icon: 'none'
    });
  } finally {
    Taro.hideLoading();
  }
};

// 处理签到
async function handleCheckin() {
  isChecking.value = true;
  console.log('===>', locationObj.value?.location);
  
  // 检查位置信息是否存在
  if (!locationObj.value?.location?.lng || !locationObj.value?.location?.lat) {
    console.log('位置信息为空，重新获取位置...');
    
    try {
      Taro.showLoading({ title: "正在获取位置..." });
      await getCurrentLocation();
      Taro.hideLoading();
    } catch (error) {
      Taro.hideLoading();
      Taro.showToast({
        title: "获取位置失败，请重试",
        icon: "none",
        duration: 2000,
      });
      isChecking.value = false;
      return;
    }
  }

  // 模拟定位过程
  setTimeout(async () => {
    // 再次检查位置信息
    if (!locationObj.value?.location?.lng || !locationObj.value?.location?.lat) {
      Taro.showToast({
        title: "位置信息获取失败",
        icon: "none",
        duration: 2000,
      });
      isChecking.value = false;
      return;
    }
    
    const res = await post("/check/checkin", {
      id: taskId,
      longitude: locationObj.value.location.lng,
      latitude: locationObj.value.location.lat,
      checkrange: 100,
    });

    if (res.code == 0) {
      isChecked.value = true;
      distance.value = 0;

      Taro.showToast({
        title: "签到成功！",
        icon: "success",
        duration: 2000,
      });
    } else {
      Taro.showToast({
        title: "签到失败，超出范围！",
        icon: "none",
        duration: 2000,
      });
    }

    isChecking.value = false;
  }, 2000);
}

/**
 * 获取当前位置
 * 优先使用微信环境，fallback到浏览器地理位置API
 */
async function getCurrentLocation() {
  return new Promise((resolve, reject) => {
    // 检查是否在微信环境中（包括微信浏览器检测）
    const isWechatBrowser = /micromessenger/i.test(navigator.userAgent);
    const hasWxAPI = typeof wx !== 'undefined' && wx.getLocation;
    
    if (isWechatBrowser && hasWxAPI) {
      console.log('检测到微信浏览器环境，使用微信API获取位置');
      
      wx.getLocation({
        type: 'gcj02',
        success: async (res) => {
          console.log('微信位置获取成功:', res);
          try {
            // 调用userStore的getAddressInfo获取详细地址信息
            const addressInfo = await userStore.getAddressInfo(res.latitude, res.longitude, "wx-sdk");
            locationObj.value = addressInfo;
            logLocationUpdate("wx-sdk", addressInfo);
            resolve(addressInfo);
          } catch (error) {
            console.error('地址解析失败:', error);
            // 即使地址解析失败，也保存基本的经纬度信息
            locationObj.value = {
              location: {
                lat: res.latitude,
                lng: res.longitude
              },
              address: '位置获取成功',
              adInfo: null
            };
            logLocationUpdate("wx-sdk-fallback", locationObj.value);
            resolve(locationObj.value);
          }
        },
        fail: (error) => {
          console.error('微信位置获取失败:', error);
          // 降级到浏览器API
          getBrowserLocation().then(resolve).catch(reject);
        }
      });
    } else {
      console.log('非微信浏览器环境或微信API不可用，使用浏览器地理位置API');
      console.log('环境检测:', { isWechatBrowser, hasWxAPI });
      getBrowserLocation().then(resolve).catch(reject);
    }
  });
}

/**
 * 使用浏览器地理位置API获取位置
 */
async function getBrowserLocation() {
  return new Promise((resolve, reject) => {
    if (!navigator.geolocation) {
      reject(new Error('浏览器不支持地理位置获取'));
      return;
    }
    
    console.log('使用浏览器地理位置API获取位置');
    
    navigator.geolocation.getCurrentPosition(
      async (position) => {
        const { latitude, longitude } = position.coords;
        console.log('浏览器位置获取成功:', { latitude, longitude });
        
        try {
          // 调用userStore的getAddressInfo获取详细地址信息
          const addressInfo = await userStore.getAddressInfo(latitude, longitude, "browser");
          locationObj.value = addressInfo;
          logLocationUpdate("browser", addressInfo);
          resolve(addressInfo);
        } catch (error) {
          console.error('地址解析失败:', error);
          // 即使地址解析失败，也保存基本的经纬度信息
          locationObj.value = {
            location: {
              lat: latitude,
              lng: longitude
            },
            address: '位置获取成功',
            adInfo: null
          };
          logLocationUpdate("browser-fallback", locationObj.value);
          resolve(locationObj.value);
        }
      },
      (error) => {
        console.error('浏览器位置获取失败:', error);
        let errorMessage = '位置获取失败';
        
        switch (error.code) {
          case error.PERMISSION_DENIED:
            errorMessage = '用户拒绝了位置权限请求';
            break;
          case error.POSITION_UNAVAILABLE:
            errorMessage = '位置信息不可用';
            break;
          case error.TIMEOUT:
            errorMessage = '位置获取超时';
            break;
          default:
            errorMessage = '未知的位置获取错误';
            break;
        }
        
        reject(new Error(errorMessage));
      },
      {
        enableHighAccuracy: true,
        timeout: 10000,
        maximumAge: 60000
      }
    );
  });
}

// 计算两点之间的距离（米）
const calculateDistance = (lat1, lng1, lat2, lng2) => {
  const R = 6371000; // 地球半径（米）
  const dLat = (lat2 - lat1) * Math.PI / 180;
  const dLng = (lng2 - lng1) * Math.PI / 180;
  const a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
    Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) *
    Math.sin(dLng / 2) * Math.sin(dLng / 2);
  const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
  return R * c;
};

// 检查签到状态
const checkCheckinStatus = async () => {
  // try {
  //   const res = await post('/check/status', {
  //     id: taskId
  //   });
    
  //   if (res.code === 0) {
  //     isChecked.value = res.data.isChecked || false;
  //     if (isChecked.value) {
  //       Taro.showToast({
  //         title: '今日已签到',
  //         icon: 'success'
  //       });
  //     }
  //   }
  // } catch (error) {
  //   console.error('检查签到状态失败:', error);
  // }
};

// 刷新位置和距离
const refreshLocation = async () => {
  try {
    Taro.showLoading({ title: '刷新位置中...' });
    await getCurrentLocation();
    
    if (locationObj.value?.location && currentTask.value.latitude && currentTask.value.longitude) {
      const dist = calculateDistance(
        locationObj.value.location.lat,
        locationObj.value.location.lng,
        currentTask.value.latitude,
        currentTask.value.longitude
      );
      distance.value = Math.round(dist);
      
      Taro.showToast({
        title: `距离：${distance.value}米`,
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('刷新位置失败:', error);
    Taro.showToast({
      title: '位置刷新失败',
      icon: 'none'
    });
  } finally {
    Taro.hideLoading();
  }
};

// 获取页面参数中的职位ID和类型
const taskId = Taro.getCurrentInstance().router?.params.id;
const taskType = Taro.getCurrentInstance().router?.params.type || '3'; // 默认为签到任务类型
const tid = ref(taskId);

// 页面加载时获取职位详情
const onLoad = async () => {
  console.log("任务ID：", taskId);
  if (taskId) {
    try {
      Taro.showLoading({ title: "加载中..." });
      const res = await post("/check/detail", { id: taskId });
      console.log("res", res);
      currentTask.value = res.data.columns;
      console.log("currentTask", currentTask);
      
      if (res.code === 0) {
        currentTask.value = res.data.columns;
        console.log("currentTask", currentTask);
        
        // 判断用户身份
        isPublisher.value = currentTask.value.member_id == userInfo.value.id;
        isExecutor.value = res.data.columns.members?.some((item) => 
          item.columns.member_id === userInfo.value.id?.toString() && item.columns.status === 11
        ) || false;
        
        // 设置总金额为任务金额
        totalAmount.value = currentTask.value.task_amount || 0;
        
        // 检查签到状态
        await checkCheckinStatus();
        // 获取当前位置并计算距离
        await getCurrentLocation();
        if (locationObj.value?.location && currentTask.value.latitude && currentTask.value.longitude) {
          const dist = calculateDistance(
            locationObj.value.location.lat,
            locationObj.value.location.lng,
            currentTask.value.latitude,
            currentTask.value.longitude
          );
          distance.value = Math.round(dist);
        }
      } else {
        showToast({ title: "获取职位信息失败", icon: "none" });
      }
    } catch (error) {
      showToast({ title: "网络错误，请重试", icon: "none" });
    } finally {
      Taro.hideLoading();
    }
  }
};

onLoad();

// 刷新数据函数（不显示loading）
const refreshData = async () => {
  console.log("任务ID：", taskId);
  if (taskId) {
    try {
      const res = await post("/check/detail", { id: taskId });
      console.log("res", res);
      currentTask.value = res.data.columns;
      console.log("currentTask", currentTask);
      
      if (res.code === 0) {
        currentTask.value = res.data.columns;
        console.log("currentTask", currentTask);
        
        // 判断用户身份
        isPublisher.value = currentTask.value.member_id == userInfo.value.id;
        isExecutor.value = res.data.columns.members?.some((item) => 
          item.columns.member_id === userInfo.value.id?.toString() && item.columns.status === 11
        ) || false;
        
        // 设置总金额为任务金额
        totalAmount.value = currentTask.value.task_amount || 0;
        
        // 检查签到状态
        await checkCheckinStatus();
        // 获取当前位置并计算距离
        await getCurrentLocation();
        if (locationObj.value?.location && currentTask.value.latitude && currentTask.value.longitude) {
          const dist = calculateDistance(
            locationObj.value.location.lat,
            locationObj.value.location.lng,
            currentTask.value.latitude,
            currentTask.value.longitude
          );
          distance.value = Math.round(dist);
        }
      } else {
        showToast({ title: "获取职位信息失败", icon: "none" });
      }
    } catch (error) {
      showToast({ title: "网络错误，请重试", icon: "none" });
    }
  }
};

// 下拉刷新处理
const onPullDownRefresh = async () => {
  const t = tid.value;
  tid.value = '';
  await new Promise(r => setTimeout(r, 90));

  try {
    // 使用专门的刷新函数，不显示loading
    await refreshData();
    
    // 更新 refreshKey 来触发 role 组件重新渲染
    refreshKey.value++;
    
    // 添加短暂延迟确保数据更新完成
    await new Promise(r => setTimeout(r, 100));
    
    showToast({ title: "刷新成功", icon: "success" });
  } catch (error) {
    console.error("下拉刷新失败:", error);
    showToast({ title: "刷新失败，请重试", icon: "none" });
  } finally {
    // 确保动画停止
    Taro.stopPullDownRefresh();
  }
  
  tid.value = t;
};

// 注册下拉刷新
Taro.usePullDownRefresh(onPullDownRefresh);

Taro.useDidShow(async () => {
  tid.value = '';
  await new Promise(r => setTimeout(r, 90));
  onLoad();
});
</script>

<style lang="scss">
.detail-value{
  font-size: 28rpx;
  color: #999;
}
.nut-popup{
  border-radius: 20rpx;
}
</style>
